package com.lepu.app.fun.mother_circle.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.AppEnterTongJi;
import com.app.utils.BitmapLoadUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.MotherCircleAllActivity;
import com.lepu.app.fun.mother_circle.MotherTopicActivity;
import com.lepu.app.fun.mother_circle.bean.BeanMotherCircle;
import com.lepu.app.fun.mother_circle.fragment.FragmentMotherCircle;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;

public class AdapterMotherCircle extends BaseAdapter implements AsyncRequest{

	private LayoutInflater mLayoutInflater = null;
	private Context mContext = null;
	private ArrayList<BeanMotherCircle> mArrayList = null;
	private String mContextClass = null;
	
	private String REQUEST_CIRCLE = "request_circle";
	private String REQUEST_CIRCLE_EXIT = "request_circle_exit";
	private static final int MSG_CIRCLE_SUCESS = 11;
	private static final int MSG_CIRCLE_FAIL = 12;
	private static final int MSG_CIRCLE_EXIT_SUCESS = 13;
	private static final int MSG_CIRCLE_EXIT_FAIL = 14;
	

	public AdapterMotherCircle(Context context,ArrayList<BeanMotherCircle> arrayList,String contextClass) {

		mContext = context;
		mLayoutInflater = LayoutInflater.from(context);
		mArrayList = arrayList;
		mContextClass = contextClass;
	}

	@Override
	public int getCount() {
		int size = 0;
		if (mArrayList != null && mArrayList.size() > 0) {
			size = mArrayList.size();
		}
		return size;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint({ "InflateParams", "NewApi" })
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		final ViewHolder holder;

		if (convertView == null) {
			convertView = mLayoutInflater.inflate(R.layout.mother_circle_listitem, null);

			holder = new ViewHolder();

			LinearLayout mainItemLayout = (LinearLayout) convertView.findViewById(R.id.mainItemLayout);
			ImageView iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView);
			TextView titleTextView = (TextView) convertView.findViewById(R.id.titleTextView);
			TextView titleTypeTextView = (TextView) convertView.findViewById(R.id.titleTypeTextView);
			
			TextView peopleCountTextView = (TextView) convertView.findViewById(R.id.peopleCountTextView);
			TextView topicCountTextView = (TextView) convertView.findViewById(R.id.topicCountTextView);
			ImageView cricleAddImageView = (ImageView) convertView.findViewById(R.id.circleAddImageView);
			

			holder.mainItemLayout = mainItemLayout;
			holder.iconImageView = iconImageView;
			holder.titleTextView = titleTextView;
			holder.titleTypeTextView = titleTypeTextView;
			
			holder.peopleCountTextView = peopleCountTextView;
			holder.topicCountTextView = topicCountTextView;
			holder.cricleAddImageView = cricleAddImageView;
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		holder.mainItemLayout.setTag(position);

		final BeanMotherCircle item = mArrayList.get(position);

		//UniversalImageLoadTool.disPlay(item.cricleAvatar, holder.iconImageView, R.drawable.default_icon_small);
		BitmapLoadUtil.displayImage( R.drawable.default_icon_small,item.cricleAvatar,holder.iconImageView);

	    holder.titleTextView.setText(item.cricleName);
	    holder.titleTypeTextView.setText(item.ParentTCTitle);
		holder.peopleCountTextView.setText(item.criclePeopleCount+"  人");
		holder.topicCountTextView.setText(item.cricleTopicCount+"  话题");
		
		if(item.cricleType == 1){ //已加入圈子
			if(mContextClass.equals("MotherCircleAllActivity")){
				holder.cricleAddImageView.setBackground(mContext.getResources().getDrawable(R.drawable.mother_circle_has_icon));
			}else{
				holder.cricleAddImageView.setVisibility(View.GONE);
				holder.mainItemLayout.setOnLongClickListener(new OnLongClickListener() {
					
					@Override
					public boolean onLongClick(View arg0) {
						new MyDialog(MainTabActivity.getInstance())
		                .setMessage("您确定退出该圈子吗?")
		                .setNegativeButton(R.string.app_cancel,
		                        new View.OnClickListener() {

		                            @Override
		                            public void onClick(View v) {

		                            }
		                        })
		                .setPositiveButton(R.string.app_ok,
		                        new View.OnClickListener() {

		                            @Override
		                            public void onClick(View v) {
		                            	
		                            	AppEnterTongJi.clickEvent(51, "");
		                           	 requestExitCircle(item.cricleID);
		                               
		                            }
		                        }).create(null).show();
						
						return false;
					}
				});
			}
		}else{
			holder.cricleAddImageView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					
					AppEnterTongJi.clickEvent(50, "");
					
					boolean flagLogin = MainTabActivity.jumpLogin((BaseFragmentActivity)mContext);
					
					if(flagLogin){
						return;
					}
					
					requestAddCircle(item.cricleID);
				}
			});
		}
		
		holder.mainItemLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(mContext,MotherTopicActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("motherCircle", item);
				intent.putExtras(bundle);
				if(mContextClass.equals("MotherCircleAllActivity")){
					((MotherCircleAllActivity)mContext).startActivity(intent, true);
				}else{
					MainTabActivity.getInstance().startActivity(intent, true);
				}
			}
		});

		return convertView;
	}

	public void requestAddCircle(String circleId) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);
			} else {
				params.put("UserID", -1);
				params.put("LoginToken", "");
			}
			
			params.put("CategoryID", circleId);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getCircleAddUrl(), map, null, this,REQUEST_CIRCLE, true, true);
		MainTabActivity.getInstance().showProgressDialog();
	}
	
	public void requestExitCircle(String circleId) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);
			} else {
				params.put("UserID", -1);
				params.put("LoginToken", "");
			}
			
			params.put("CategoryID", circleId);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getCircleExitUrl(), map, null, this,REQUEST_CIRCLE_EXIT, true,true);
		MainTabActivity.getInstance().showProgressDialog();
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_CIRCLE_SUCESS:
				String dataString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(dataString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						
						if(mContextClass.equals("MotherCircleAllActivity")){
							MotherCircleAllActivity.getInstance().request();
							FragmentMotherCircle.getInstance().request();
						}else if(mContextClass.equals("FragmentMotherCircle")){
							FragmentMotherCircle.getInstance().request();
						}
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				MainTabActivity.getInstance().hideProgressDialog();
				break;

			case MSG_CIRCLE_FAIL:
				MainTabActivity.getInstance().hideProgressDialog();
				break;
			case MSG_CIRCLE_EXIT_SUCESS:
				MainTabActivity.getInstance().hideProgressDialog();
				
				FragmentMotherCircle.getInstance().request();
				break;

			case MSG_CIRCLE_EXIT_FAIL:
				MainTabActivity.getInstance().hideProgressDialog();
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if(object.equals(REQUEST_CIRCLE)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_CIRCLE_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}
		else if(object.equals(REQUEST_CIRCLE_EXIT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_CIRCLE_EXIT_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int arg1, String arg2) {
		if(object.equals(REQUEST_CIRCLE)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_CIRCLE_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_CIRCLE_EXIT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_CIRCLE_EXIT_FAIL;
			mHandler.sendMessage(msg);
		}
		
	}
	
	private static class ViewHolder {
		LinearLayout mainItemLayout;
		ImageView iconImageView;
		TextView titleTextView;
		TextView titleTypeTextView;
		TextView peopleCountTextView;
		TextView topicCountTextView;
		
		ImageView cricleAddImageView;
	}
}
